<template>
  <div class="flex flex-col h-full">
    <a-card>
      <div class="flex justify-between items-center">
        <a-button type="primary" class="mr-4" @click="router.go(-1)"> 返回 </a-button>
        <a-descriptions class="mt-3" :column="4">
          <a-descriptions-item label="单号"> {{ formState?.jhdh || '-' }}</a-descriptions-item>
          <a-descriptions-item label="计划日期">{{ formState?.jhrq || '-' }}</a-descriptions-item>
          <a-descriptions-item label="供应商"> {{ formState?.gysmc || '-' }}</a-descriptions-item>
          <!-- <a-descriptions-item label="类别"> {{ formState?.djlb === '0' ? '药材' : '物资' }}</a-descriptions-item> -->
          <a-descriptions-item label="制单人">{{ formState?.createUser || '-' }}</a-descriptions-item>
          <a-descriptions-item label="制单时间"> {{ formState?.createTime || '-' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-card>
    <a-card class="mt-2 flex-1">
      <div class="flex justify-end">
        <a-button class="mr-2 mb-2" type="link" @click="addRow()"> 自动生成采购计划明细 </a-button>
      </div>
      <BaseTable
        :data-source="dataSource"
        column-code="000142"
        :loading="loading"
        max-fill
        :extra-height="64"
        :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'NO'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'ypbh'">
            <EditCell title="物品名称">
              <SelectMedicine :value="{ mc: record.mc, gg: record.gg, cj: record.cj }" type="物资采购" @select="onSelectMedicine($event, record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'cmemo'">
            <EditCell title="备注">
              <BaseInput v-model:value="record.cmemo" @blur="editRow(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'sl'">
            <EditCell title="数量">
              <BaseInput
                v-model:value="record.sl"
                v-input:int
                v-input-selection
                class="text-right"
                :auto-focus="record.isNew && focusCell === record.key"
                placeholder="请输入"
                @blur="editRow(record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'addtime'">
            <EditCell title="添加时间">
              <a-date-picker v-model:value="record.addtime" show-time value-format="YYYY-MM-DD HH:mm:ss" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <BaseButton confirm-text="确认删除？" type="text" danger size="small" @click="onDelete(record)">删除</BaseButton>
          </template>
        </template>
        <template #footer>
          <div class="text-center sticky bottom-0">
            <a-button class="mr-2" :disabled="!formState?.jhdh" type="primary" ghost @click="addRow()"> 新增一行 </a-button>
            <a-button type="primary" :disabled="dataSource.length === 0" @click="saveNewRows()"> 保存 </a-button>
          </div>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import BaseTable from '@/components/BaseTable'
import BaseButton from '@/components/BaseButton'
import { post } from '@/utils/request'
import EditCell from '@/components/EditCell'

const formState = ref({})
const loading = ref(false)
const dataSource = ref([])
const focusCell = ref('')
const route = useRoute()
const router = useRouter()
const editRow = (row) => !row.isNew && fetchSave(row)
const fetchSave = async (row) => {
  row.jhdh = formState.value.jhdh
  const { code, msg } = await post('/materials/psiform/doSaveSupplyPlanDetail', row)
  if (code !== 0) return message.error(msg || '操作失败')
  getDetailData()
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
}
const saveNewRows = async () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  newRow.forEach((item) => {
    if (item.ypbh && item.sl) {
      fetchSave(item)
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  })
}

const onSelectMedicine = (medicine, row) => {
  row.ypbh = medicine?.bh
  row.mc = medicine?.mc
  row.gg = medicine?.gg
  row.dw = medicine?.dw
  row.cd = medicine?.cd
  row.cj = medicine?.cj
  focusCell.value = row.key
  editRow(row)
}
//添加行
const addRow = () => {
  const key = `row-${dataSource.value.length}`
  const addRow = { key, isNew: true, addtime: dayjs().format('YYYY-MM-DD HH:mm:ss') }
  dataSource.value.push(addRow)
}

const getMainData = async () => {
  const { data, code } = await post('/materials/psiform/getSupplyPlanHeadList', {
    jhdh: route.query?.jhdh
  })
  if (code === 0) {
    formState.value = data[0]
  }
}
const getDetailData = async () => {
  loading.value = true
  const { data, code } = await post('/materials/psiform/getSupplyPlanDetailList', {
    jhdh: route.query?.jhdh
  })
  loading.value = false
  if (code === 0) {
    dataSource.value = data
  }
}
const onDelete = async (row) => {
  if (row.isNew) {
    dataSource.value = dataSource.value.filter((item) => item.key !== row.key)
  } else {
    const { code, msg } = await post('/materials/psiform/doDeleteSupplyPlanDetail', { jhmxdh: row.jhmxdh })
    code === 0 ? getDetailData() : message.error(msg || '删除失败')
  }
}

watchEffect(() => {
  if (route && route.query?.jhdh) {
    getMainData()
    getDetailData()
  }
})
</script>
<style lang="less" scoped>
:deep(.ant-card-head) {
  padding-left: 8px;
}
</style>
